import React, {forwardRef, PropsWithChildren, useImperativeHandle, useState} from 'react';
import {Drawer} from "antd";
import {DrawerProps} from "antd/lib/drawer";

/** 抽屉组件属性,属性[visible]被排除, [visible]由本组件接管控制*/
export interface XtraDrawerProps extends Omit<DrawerProps, 'visible'> {
}

/** 抽屉组件方法 */
export interface XtraDrawerMethods {
  /** 显示 */
  show: () => void;
  /** 隐藏 */
  hide: () => void;
}

/** 扩展抽屉组件 */
const XtraDrawer = forwardRef<XtraDrawerMethods, PropsWithChildren<XtraDrawerProps>>((props, ref) => {
  const {children, ...rest} = props;
  const [visible, setVisible] = useState<boolean>(false);

  //本组件方法
  const methods: XtraDrawerMethods = {
    show: () => {
      setVisible(true);
    },
    hide: () => {
      setVisible(false);
    },
  };

  //暴露给父组件的对象(属性和方法)
  useImperativeHandle(ref, () => methods, []);

  // 如果调用者未指定[onClose]回调函数,则生成默认的onClose,默认为关闭抽屉
  if (rest.onClose === undefined) {
    rest.onClose = () => {
      setVisible(false);
    };
  }
  return (
    <Drawer visible={visible} {...rest}>{children}</Drawer>
  );
});

/** 组件默认值 */
XtraDrawer.defaultProps = {
  destroyOnClose: true,
};

/** 缓存组件,只有组件的props发生变化时才会重新绘制组件 */
export default React.memo(XtraDrawer);
